package com.learning.demos;


import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicReference;

/**
 * 实现一个自旋锁
 * 循环比较直到成功为止，没有类似wait的阻塞
 *
 * 通过cas操作完成自旋锁，a线程先进来掉到
 * @author adolphw
 */
public class SpinLockDemo {
    // 原子引用线程
    AtomicReference<Thread> atomicReference = new AtomicReference<>();

    public void myLock() {
        Thread thread = Thread.currentThread();
        System.out.println(Thread.currentThread().getName()+"\t come in");

        while (!atomicReference.compareAndSet(null, thread)) {

        }


    }

    public void myUnLock() {
        Thread thread = Thread.currentThread();
        atomicReference.compareAndSet(thread, null);

        System.out.println(Thread.currentThread().getName()+"\t invoked my unlock");
    }

    public static void main(String[] args) {

        SpinLockDemo spinLockDemo = new SpinLockDemo();

        new Thread(() -> {
            spinLockDemo.myLock();

            try {
                TimeUnit.SECONDS.sleep(5);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }

            spinLockDemo.myUnLock();

        }, "AA").start();

        new Thread(() -> {
            spinLockDemo.myLock();
            spinLockDemo.myUnLock();

        }, "BB").start();
    }

}
